<script setup lang="ts">
import { onHide, onLoad, onReady, onShow, onTabItemTap, onUnload } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'
import { useMemberStore } from '@/stores'
import {
  AppleAddAPI,
  GetGoodDetailAPI,
  GetGoodsTypeAPI,
  GetGroupAPI,
  GetUserAccountAPI,
  GetUserSettingAPI,
  UpdateGoodAPI,
  type NoteParams,
} from '@/services/detail'
import type { GetGoodsTypeResponse, GoodType, UserAccount } from '@/types/detail'
import PickerAccountPanel from './PickerAccountPanel.vue'
import PickerTagPanel from './PickerTagPanel.vue'
import { GetVersionAPI, SearchFileOneAPI } from '@/services/img'
import { AddUserTagType, GetUserTagTypeAPI } from '@/services/login'

// 定义 props 接收
const query = defineProps<{
  pageType: string
  id: number
  backPage: string
  AccountNo: string //新增时，若有传账户类型，则默认传递的账户类型，否则则是用户设置的默认账户类型。
}>()
const version = ref('')
const tagGoodType = ref('标签')
const tagData = ref<string[]>([])
// 支出选项
const zhichu = ref<GoodType[]>()
//收入选项
const shouru = ref<GoodType[]>()
//默认值设置为FALSE，表示不加载
const ready = ref(false)
const backgroundImgMain = ref('')
const opacity = ref(0.7)
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const userAccounts = ref<UserAccount[]>([])
const curUserAccount = ref<UserAccount>({
  AccountNo: '',
  UserName: '',
  AccountTypeName: '',
  AccountCard: '',
  Display: '',
  Remark: '',
})
//转出账户
const outUserAccount = ref<UserAccount>({
  AccountNo: '',
  UserName: '',
  AccountTypeName: '',
  AccountCard: '',
  Display: '',
  Remark: '',
})
//转入账户
const inUserAccount = ref<UserAccount>({
  AccountNo: '',
  UserName: '',
  AccountTypeName: '',
  AccountCard: '',
  Display: '',
  Remark: '',
})
const form = ref<NoteParams>({
  UserName: '',
  AccountNo: '',
  OutAccountNo: '',
  InAccountNo: '',
  InOut: '支出',
  GoodsType: '餐饮',
  Goods: '',
  Amount: 0,
  DealTimeStr: '',
  Auth: '',
  Source: '小程序',
  IsNotYuSuan: false,
  IsAvg: false,
  IsRequire: true,
  UserGroup: '',
  IsNotMonthAccount: false,
})
const checkdata = [
  { value: true, text: '是' },
  { value: false, text: '否' },
]
const result = ref('0')
// 获取会员信息
const memberStore = useMemberStore()
onMounted(async () => {
  console.log('note_onMounted')
})
onReady(async () => {
  console.log('note_onReady')
})
onUnload(async () => {
  console.log('note_onUnload')
})
onShow(async () => {
  // const res1 = await GetVersionAPI({
  //   Auth: '',
  // })
  // if (version.value != res1.result.Version) {
  //   window.location.reload()
  // }
  //个性主题
  if (memberStore.profile) {
    const detail = await SearchFileOneAPI({
      ImgType: 'noteAccount',
      UserName: memberStore.profile.UserName,
      ID: 0,
    })
    if (detail.result) {
      backgroundImgMain.value = detail.result.ImgUrl
    }
    const setting = await GetUserSettingAPI({
      UserName: memberStore.profile.UserName,
    })
    opacity.value = setting.result.NoteAccoutOpacit / 10
  }
})
onHide(async () => {
  console.log('note_onHidden')
})
const formatDate = (date: Date) => {
  console.log('date' + date)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}` // 格式化为YYYY-MM-DD
}
//加载初始化
onLoad(async (option) => {
  const res1 = await GetVersionAPI({
    Auth: '',
    UserGroup: '',
  })
  version.value = res1.result.Version
  if (memberStore.profile) {
    await UpdateCookie()
    // uni.hideTabBar()
    form.value.DealTimeStr = getCurDate()
    form.value.UserName = memberStore.profile.UserName
    form.value.Auth = memberStore.profile.Token
    form.value.UserGroup = memberStore.profile.UserGroup
    //初始化收入、支出类型
    const res = await GetGoodsTypeAPI({
      UserName: form.value.UserName,
      Auth: memberStore.profile.Token,
    })
    const response = res.result as GetGoodsTypeResponse
    zhichu.value = response.Out
    shouru.value = response.In
    //初始化用户账号
    await InitAccountNo()
    //初始化账户
    await InitUserAccount()
    //获取当前账户
    GetUserAccount(form.value.AccountNo)
    //获取平台
    uni.getSystemInfo({
      success: function (res) {
        form.value.Source = res.platform
      },
    })
    selectGoodType('餐饮')

    ready.value = true
    if (option && option.pageType == 'update') {
      const res = await GetGoodDetailAPI({ ID: option.id })

      form.value.UserName = res.result.UserName
      form.value.AccountNo = res.result.AccountNo
      curUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == res.result.AccountNo)!
      form.value.InOut = res.result.Amount > 0 ? '收入' : '支出'
      form.value.GoodsType = res.result.GoodsType
      form.value.Goods = res.result.Goods
      form.value.Amount = res.result.Amount
      form.value.DealTimeStr = formatDate(new Date(res.result.DealTime))
      form.value.IsNotYuSuan = res.result.IsNotYuSuan
      form.value.IsAvg = res.result.IsAvg
      form.value.IsRequire = res.result.IsRequire
      form.value.IsNotMonthAccount = res.result.IsNotMonthAccount
      result.value = res.result.Amount + ''
    }
  } else {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  }
  await InitGetUserTagType()
})
//初始化用户配置
const InitAccountNo = async () => {
  if (memberStore.profile) {
    const res = await GetUserSettingAPI({ UserName: memberStore.profile.UserName })
    if (query.AccountNo) {
      form.value.AccountNo = query.AccountNo
    } else {
      form.value.AccountNo = res.result.DefaultNoteAccountNo
    }

    form.value.OutAccountNo = res.result.DefaultOutAccountNo
    form.value.InAccountNo = res.result.DefaultInAccountNo
  }
}
//更新cookie
const UpdateCookie = async () => {
  if (memberStore.profile) {
    const res = await GetGroupAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
    })
    memberStore.setProfile(res.result)
  }
}

//初始化账户列表
const InitUserAccount = async () => {
  if (memberStore.profile) {
    const res = await GetUserAccountAPI({
      UserName: memberStore.profile.UserName,
      Auth: memberStore.profile.Token,
      UserGroup: memberStore.profile.UserGroup,
    })
    userAccounts.value = res.result
  }
}
//获取用户账户名
const GetUserAccount = (accountNo: string) => {
  if (memberStore.profile) {
    console.log('form.value.OutAccountNo：' + form.value.OutAccountNo)
    console.log('form.value.InAccountNo：' + form.value.InAccountNo)
    curUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == accountNo)!
    outUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == form.value.OutAccountNo)!
    inUserAccount.value = userAccounts.value?.find((o) => o.AccountNo == form.value.InAccountNo)!
  }
}
//TabBar点击进入事件
onTabItemTap(() => {
  if (!memberStore.profile) {
    uni.showToast({ icon: 'none', title: '请先登录' })
    setTimeout(() => {
      // 页面跳转
      uni.switchTab({ url: '/pages/my/my' })
    }, 500)
  } else {
    // uni.hideTabBar()
    form.value.DealTimeStr = getCurDate()
    form.value.UserName = memberStore.profile.UserName
  }
})
//返回
const Cancel = () => {
  uni.showTabBar()
  uni.switchTab({
    url: '/pages/Detail/Detail',
  })
}
//获取当前时间
const getCurDate = () => {
  const date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  return `${year}-${month}-${day}`
}
//日期改变
const bindDateChange = (e: any) => {
  form.value.DealTimeStr = e.detail.value
}
// 计算器-添加
const cal = (str: string) => {
  result.value = (result.value + str).replace(/^0+/, '')
  if (result.value.startsWith('.')) {
    result.value = '0' + result.value
  }
  if (result.value == '') {
    result.value = '0'
  }
}
const calculate = () => {
  try {
    result.value = eval(result.value) + ''
  } catch (error) {
    uni.showToast({ icon: 'none', title: '无效的表达式' })
  }
}
//计算器-取消
const back = () => {
  result.value = result.value.substring(0, result.value.length - 1)
  if (result.value == '') {
    result.value = '0'
  }
}
const clear = () => {
  result.value = '0'
}
//计算器-完成
const ok = async () => {
  form.value.Amount = Number.parseFloat(result.value)
  if (query.pageType == 'update') {
    await UpdateGoodAPI({
      ID: query.id,
      UserName: form.value.UserName,
      AccountNo: form.value.AccountNo,
      OutAccountNo: form.value.OutAccountNo,
      InAccountNo: form.value.InAccountNo,
      InOut: form.value.InOut,
      GoodsType: form.value.GoodsType,
      Goods: form.value.Goods,
      Amount: form.value.Amount,
      DealTimeStr: form.value.DealTimeStr,
      Auth: form.value.Auth,
      Source: form.value.Source,
      IsNotYuSuan: form.value.IsNotYuSuan,
      IsAvg: form.value.IsAvg,
      IsRequire: form.value.IsRequire,
      UserGroup: form.value.UserGroup,
      IsNotMonthAccount: form.value.IsNotMonthAccount,
    })
    uni.showToast({ icon: 'success', title: '更新成功' })
    result.value = '0'
    form.value.Goods = ''
    uni.switchTab({
      url: '/pages/Detail/Detail',
    })
  } else {
    const res = await AppleAddAPI(form.value)
    uni.showToast({ icon: 'success', title: '新增成功' })
    result.value = '0'
    form.value.Goods = ''
  }
}
//选择账户
const pickerAccountChange = (e: any) => {
  console.log(e)
  curUserAccount.value = e
  form.value.AccountNo = curUserAccount.value.AccountNo
}
//选择备注
const pickerTagChange = (e: any) => {
  form.value.Goods = tagData.value[e.detail.value]
}
//转出账户
const pickerOutAccountChange = (e: any) => {
  outUserAccount.value = e
  form.value.OutAccountNo = outUserAccount.value.AccountNo
}
//转入账户
const pickerInAccountChange = (e: any) => {
  inUserAccount.value = e
  form.value.InAccountNo = inUserAccount.value.AccountNo
}
//选择类型
const inOutChange = async (inout: string) => {
  form.value.InOut = inout
  if (inout == '支出') {
    selectGoodType('餐饮')
  } else if (inout == '收入') {
    selectGoodType('工资')
  } else {
    form.value.Goods = ''
  }
  await InitGetUserTagType()
}
const onIsNotYuSuan = (e: any) => {
  console.log(e)
  form.value.IsNotYuSuan = e.detail.value[0] || false
  if (form.value.IsNotYuSuan) {
    form.value.IsAvg = false
  }
}
const onIsAvg = (e: any) => {
  console.log(e)
  form.value.IsAvg = e.detail.value[0] || false
  if (form.value.IsAvg) {
    form.value.IsNotYuSuan = false
  }
}
const onIsRequire = (e: any) => {
  form.value.IsRequire = e.detail.value[0] || false
}
const onIsNotMonthAccount = (e: any) => {
  form.value.IsNotMonthAccount = e.detail.value[0] || false
}

//返回
const Onleft = () => {
  //格式：'/pages/card/cardEdit'
  uni.reLaunch({ url: query.backPage })
}
//初始化快捷标签
const InitGetUserTagType = async () => {
  if (memberStore.profile?.UserName) {
    const res = await GetUserTagTypeAPI({
      Auth: memberStore.profile!.Token,
      UserName: memberStore.profile!.UserName,
      InOut: form.value.InOut == '收入' ? 1 : 2,
      GoodsType: form.value.GoodsType,
    })
    tagData.value = []
    for (var i = 0; i < res.result.length; i++) {
      tagData.value.push(res.result[i].TagName)
    }
  }
}
//添加标签
const addTag = async () => {
  if (memberStore.profile) {
    await AddUserTagType({
      IsAdd: false,
      UserName: memberStore.profile.UserName,
      InOut: form.value.InOut == '收入' ? 1 : 2,
      TagName: form.value.Goods,
      OrderBy: 0,
      ID: 0,
      GoodsType: form.value.GoodsType,
      Display: '',
    })
    // 成功提示
    uni.showToast({ icon: 'success', title: '加入标签成功' })
    await InitGetUserTagType()
  }
}
//添加商品类型
const addGoodType = async () => {
  if (memberStore.profile) {
    uni.reLaunch({
      url: '/pages/NoteAcount/GoodType?inout=' + (form.value.InOut == '收入' ? 1 : 2),
    })
  }
}

//返回
const selectGoodType = async (goodsTypeName: string) => {
  form.value.GoodsType = goodsTypeName
  if (!query.id) {
    const date = new Date()
    const hour = date.getHours()
    if (goodsTypeName == '餐饮' && !form.value.Goods) {
      console.log(hour)
      if (hour < 11) {
        form.value.Goods = '早餐'
      } else if (hour < 17) {
        form.value.Goods = '午餐'
      } else {
        form.value.Goods = '晚餐'
      }
    }
    if (goodsTypeName != '餐饮') {
      if (form.value.Goods == '早餐' || form.value.Goods == '午餐' || form.value.Goods == '晚餐') {
        form.value.Goods = ''
      }
    }
  }

  await InitGetUserTagType()
}
</script>
<template>
  <view class="viewport">
    <view class="header" :style="{ paddingTop: safeAreaInsets!.top + 'px' }">
      <view v-if="query.backPage" class="left icon-left" @tap="Onleft()"></view>
      <view class="tabs">
        <text @tap="inOutChange('支出')" class="text" :class="{ active: '支出' === form.InOut }"
          >支出</text
        >
        <text @tap="inOutChange('收入')" class="text" :class="{ active: '收入' === form.InOut }"
          >收入</text
        >
        <text @tap="inOutChange('转账')" class="text" :class="{ active: '转账' === form.InOut }"
          >转账</text
        >
      </view>
      <!-- <navigator @tap="Cancel" hover-class="none" class="cancel">返回</navigator> -->
    </view>
    <scroll-view enable-back-to-top scroll-y v-if="form.InOut === '支出'">
      <view class="category">
        <view
          v-for="item in zhichu"
          :key="item.GoodsTypeName"
          class="navigator"
          hover-class="none"
          @tap="selectGoodType(item.GoodsTypeName)"
        >
          <view
            v-if="item.GoodsIcon.startsWith('icon')"
            class="circle"
            :class="[item.GoodsIcon, { circleActive: item.GoodsTypeName === form.GoodsType }]"
          ></view>
          <view
            v-else
            class="circle bold"
            :class="{ circleActive: item.GoodsTypeName === form.GoodsType }"
            >{{ item.GoodsIcon }}</view
          >
          <view class="name">{{ item.GoodsTypeName }}</view>
        </view>
        <view class="navigator"> <view class="circle bold" @tap="addGoodType"> +</view></view>
      </view>
    </scroll-view>
    <scroll-view enable-back-to-top scroll-y v-if="form.InOut === '收入'">
      <view class="category">
        <view
          v-for="item in shouru"
          :key="item.GoodsTypeName"
          class="navigator"
          hover-class="none"
          @tap="selectGoodType(item.GoodsTypeName)"
        >
          <view
            v-if="item.GoodsIcon.startsWith('icon')"
            class="circle"
            :class="[item.GoodsIcon, { circleActive: item.GoodsTypeName === form.GoodsType }]"
          ></view>
          <view
            v-else
            class="circle bold"
            :class="{ circleActive: item.GoodsTypeName === form.GoodsType }"
            >{{ item.GoodsIcon }}</view
          >
          <view class="name">{{ item.GoodsTypeName }}</view>
        </view>
        <view class="navigator"> <view class="circle bold" @tap="addGoodType"> +</view></view>
      </view>
    </scroll-view>
    <scroll-view enable-back-to-top scroll-y v-if="form.InOut === '转账'">
      <view class="zhuanzhang">
        <view class="out">
          <PickerAccountPanel
            v-if="ready"
            @change="pickerOutAccountChange"
            :userAccounts="userAccounts"
            :curUserAccount="outUserAccount"
          ></PickerAccountPanel>
        </view>
        <view class="icon-down"> </view>
        <view class="in">
          <PickerAccountPanel
            v-if="ready"
            @change="pickerInAccountChange"
            :userAccounts="userAccounts"
            :curUserAccount="inUserAccount"
          ></PickerAccountPanel>
        </view>
      </view>
    </scroll-view>
    <view class="bottomBar">
      <view
        class="bottomBar1"
        :style="`background: url('${backgroundImgMain}')  no-repeat center / cover;opacity: ${opacity}`"
      ></view>
      <view class="resultGroup">
        <view class="icon-huitui back" @tap="back"></view>
        <view class="remark">
          <input class="uni-input" placeholder="点击填写备注" v-model="form.Goods" />
        </view>
        <view @tap="clear" class="result">{{ result }}</view>
      </view>
      <view>
        <!-- <picker
          @change="pickerAccountChange"
          mode="selector"
          :range="userAccounts"
          range-key="Display"
        >
          <text class="account">{{ curUserAccount?.Display }}</text></picker
        > -->
        <view class="selecttag">
          <PickerAccountPanel
            v-if="ready && (form.InOut == '收入' || form.InOut == '支出')"
            @change="pickerAccountChange"
            :userAccounts="userAccounts"
            :curUserAccount="curUserAccount"
          ></PickerAccountPanel>
          <picker
            v-if="ready && (form.InOut == '收入' || form.InOut == '支出')"
            class="pickerList"
            @change="pickerTagChange"
            mode="selector"
            :range="tagData"
            range-key="Display"
          >
            <text class="account" v-if="tagData.length">标签({{ tagData.length }})</text></picker
          >
          <view class="tagadd" @tap="addTag">加入标签</view>
        </view>
        <view class="selecttag">
          <checkbox-group class="isnotyusuan" @change="onIsAvg">
            <label>
              <checkbox :value="true" :checked="form.IsAvg" />

              分摊</label
            >
          </checkbox-group>

          <checkbox-group @change="onIsNotYuSuan" class="isnotyusuan">
            <label>
              <checkbox :value="true" :checked="form.IsNotYuSuan" />

              不计入预算</label
            >
          </checkbox-group>
          <checkbox-group class="isnotyusuan" @change="onIsNotMonthAccount">
            <label>
              <checkbox :value="true" :checked="form.IsNotMonthAccount" />

              不计入月账单</label
            >
          </checkbox-group>
          <checkbox-group class="isnotyusuan" @change="onIsRequire">
            <label>
              <checkbox :value="true" :checked="form.IsRequire" />

              刚需</label
            >
          </checkbox-group>
        </view>
        <view class="row">
          <view class="col" @tap="cal('7')">
            <text class="text">7</text>
          </view>
          <view class="col" @tap="cal('8')">
            <text class="text">8</text>
          </view>
          <view class="col" @tap="cal('9')">
            <text class="text">9</text>
          </view>
          <view class="col">
            <picker
              mode="date"
              :value="form.DealTimeStr"
              start="2024-01-01"
              end="2034-12-30"
              @change="bindDateChange"
            >
              <view class="text">{{ form.DealTimeStr }}</view></picker
            >
          </view>
        </view>
        <view class="row">
          <view class="col" @tap="cal('4')">
            <text class="text">4</text>
          </view>
          <view class="col" @tap="cal('5')">
            <text class="text">5</text>
          </view>
          <view class="col" @tap="cal('6')">
            <text class="text">6</text>
          </view>
          <view class="col" @tap="cal('+')">
            <text class="text">+</text>
          </view>
        </view>
        <view class="row">
          <view class="col" @tap="cal('1')">
            <text class="text">1</text>
          </view>
          <view class="col" @tap="cal('2')">
            <text class="text">2</text>
          </view>
          <view class="col" @tap="cal('3')">
            <text class="text">3</text>
          </view>
          <view class="col" @tap="cal('-')">
            <text class="text">-</text>
          </view>
        </view>
        <view class="row">
          <view class="col" @tap="ok">
            <text class="complete">完成</text>
          </view>
          <view class="col" @tap="cal('0')">
            <text class="text">0</text>
          </view>
          <view class="col" @tap="cal('.')">
            <text class="text">.</text>
          </view>
          <view class="col" @tap="calculate()">
            <text class="text">=</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './styles/noteacount.scss';
</style>
